﻿using System;
using System.Collections.Generic;
using System.Windows.Input;
using XamlInspector.Foundation;
using XamlInspector.Model;
using XamlInspector.Services;

namespace XamlInspector.Presentation
{
    public class EventViewModel : ViewModelBase
    {
        private XamlElement _element;
        private readonly List<XamlEvent> _events = new List<XamlEvent>();
        private readonly EventService _eventService;

        public EventViewModel(EventService eventService)
        {
            _eventService = eventService;
            _eventService.EventOccured += EventServiceOnEventOccured;
            Events = new ListCollectionView(_events);

            ClearCommand = new Command(Clear);
        }

        public ICollectionViewEx Events { get; private set; }

        public ICommand ClearCommand { get; private set; }

        public void UpdateSelectedElement(XamlElement element)
        {
            _eventService.StopMonitoring(_element);
            _element = element;
            if (element != null)
            {
                _eventService.StartMonitoring(element);
            }
        }

        private void Clear()
        {
            _events.Clear();
            Events.Refresh();
        }

        private void EventServiceOnEventOccured(object sender, EventArgs<XamlEvent> e)
        {
            _events.Insert(0, e.Data);
            Events.Refresh();
        }

    }
}
